home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
vol_400
/
422_02
/
misc
/
prime1.c
< prev
next >
Wrap
C/C++ Source or Header
|
1994-03-20
|
920b
|
37 lines
/*
* Much faster program for finding prime numbers. Each number is tested
* against previous primes, and the search is terminated when the
* square of the previous prime exceeds the number being tested.
*
* Note: 1 and 2 are neither tested nor displayed by this program.
*
* Compile command: cc prime1 -fop
*/
#include <stdio.h>
#define MAXPRIME 1000 /* Search up to here */
unsigned primes[MAXPRIME/2], squares[MAXPRIME/2], count = 0;
/*
* Main (and only) function
*/
main()
{
unsigned num, test;
char flag;
for(num=3; num < MAXPRIME; num += 2) { /* Test range */
flag = 1;
for(test = 0; test < count; ++test) {
if(squares[test] > num) /* Out of range */
break;
if(!(num % primes[test])) { /* No remainder - Not prime */
flag = 0;
break; } }
if(flag) {
printf("%d\n", num);
primes[count] = num;
squares[count++] = num*num; } }
}